﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Win.Controls;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Util.Log;
using PlanningGIS.DataConvert.model;
using PlanningGIS.Framework;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using DevComponents.DotNetBar.SuperGrid;
using PlanningGIS.ManageUtility.Modules;
using System.ComponentModel.Design;
using System.Windows;

namespace PlanningGIS.DataConvert
{
    /// <summary>
    /// 根据代码入库
    /// </summary>
    public partial class CtlImpFCode : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CtlImpFCode()
        {
            if (!this.DesignMode)
            {
                InitializeComponent();
            }          
        }

        /// <summary>
        /// 源数据表列表控件列名
        /// </summary>
        const string _clnSrcName = "clnSrcName";

        /// <summary>
        /// 目标数据表列表控件列名
        /// </summary>
        const string _clnAimName = "clnAimName";

        /// <summary>
        /// 源数据表字段列表控件列名
        /// </summary>
        const string _clnSrcFdName = "clnSrcFdName";

        /// <summary>
        /// 目标数据表字段列表控件列名
        /// </summary>
        const string _clnAimFdName = "clnAimFdName";

        /// <summary>
        /// 建库方案规则
        /// </summary>
        private DataImportRule _Rule = null;

        /// <summary>
        /// 要入库的源数据
        /// </summary>
        private List<IFeatureClass> _SourceDataSets = null;

        /// <summary>
        /// 数据入库操作
        /// </summary>
        private ImpJob _Job = null;

        /// <summary>
        /// 目标数据工作空间
        /// </summary>
        private IWorkspace _WorkspaceTarget = null;

        /// <summary>
        /// 目标数据要素类集合
        /// </summary>
        private List<IFeatureClass> _TargetFeatClses = null;

        /// <summary>
        /// 加载控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CtlImpFCode_Load(object sender, EventArgs e)
        {
            ctlRefXY.DefaultPath = AppConfig.CoordinatePath;
        }

        /// <summary>
        /// 按图层入库本地数据
        /// </summary>
        private bool ImpDataByLyr = false;

        /// <summary>
        /// 数据选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlDataSetList_SelectChanged(object sender, EventArgs e)
        {
            ctlRefXY.Spatials = ctlDataSetList.SpatialRefs;            
        }

        /// <summary>
        /// 入库
        /// </summary>
        public void Import()
        {
            if (!ValiadParam()) return;
            _Job = new ImpJob()
            {
                SpatialRef = ctlRefXY.SpatialRef,
                ImportRule = _Rule,
                FeatureClassSource = _SourceDataSets,
                ProgressAll = new Progressor() { ProgressBar = pgrbarAll },
                ProgressSub = new Progressor() { ProgressBar = pgrbarSub }
            };
            try
            {
                if (_WorkspaceTarget != null)
                    _Job.WorkspaceTarget = _WorkspaceTarget;
                if (_Job.WorkspaceTarget == null)
                {
                    MsgHelper.ShowErrorMsgbox(this.ParentForm, "目标工作空间创建或打开失败，请修改建库方案。");
                    return;
                }
                bool suc;
                suc = _Job.Import();
                Log log = new Log()
                {
                    USER_ID = FrameworkHelper.CurrentUser.ID,
                    USER_NAME = FrameworkHelper.CurrentUser.Name,
                    OP_TYPE = PlanningGIS.ManageUtility.Modules.zjgisLogType.AccessData,
                    NOTES = "申请导入数据",
                    OP_STATUS = zjgisLogStatus.Fail,
                };

                if (suc)
                {
                    log.NOTES = "导入数据成功。";
                    log.OP_STATUS = zjgisLogStatus.Success;
                    MsgHelper.ShowInfomationMsgbox("导入数据成功。\n");
                }
                else
                {
                    MsgHelper.ShowInfomationMsgbox("部分数据未入库成功，请查看日志信息。\n");
                }
                Log.WriteLog(log);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, "目标工作空间创建或打开失败，请修改建库方案。" + ex.Message);
                return;
            }             
        }

        /// <summary>
        /// 验证参数是否正确
        /// </summary>
        /// <returns></returns>
        private bool ValiadParam()
        {
            _Rule = ctlImpRule.Rule;
            if (_Rule == null)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, "请选择建库方案！");
                return false;
            }
            if (string.IsNullOrWhiteSpace(_Rule.SourceFieldName))
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, "请设置入库依据字段！");
                return false;
            }
            if (_Rule.dlgTargetFeatureClasses == null || _Rule.dlgTargetFeatureClasses.Count == 0)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, "建库方案中不存在目标要素类，请检查建库方案！");
                return false;
            }
            _SourceDataSets = ctlDataSetList.Datasets;
            if (_SourceDataSets == null || _SourceDataSets.Count == 0)
            {
                MsgHelper.ShowErrorMsgbox(this.ParentForm, "请选设置要入库的数据源！");
                return false;
            }
            return true;
        }
        

        /// <summary>
        /// 停止入库
        /// </summary>
        public void Stop()
        {
            if (_Job != null) _Job.Stop();
        }

        #region 字段匹配

        ///// <summary>
        ///// （根据建库规则）自动匹配要入库的图层与字段
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void btnMatch_Click(object sender, EventArgs e)
        //{
        //    if (!ValiadParam(false)) return;
        //    _WorkspaceTarget = null;
        //    superGrdFields.PrimaryGrid.AllowRowDelete = true;
        //    for (int i = superGrdFields.PrimaryGrid.Rows.Count - 1; i >= 0; i--)
        //    {
        //        superGrdFields.PrimaryGrid.Rows.Remove(superGrdFields.PrimaryGrid.Rows[i]);
        //    }   
        //    GridComboBoxExEditControl colaimname = superGrdFields.PrimaryGrid.Columns[_clnAimName].EditControl as GridComboBoxExEditControl;
        //    colaimname.DataSource = _Rule.dlgTargetFeatureClasses;
        //    colaimname.DisplayMember = "FeatureClassName";
        //    colaimname.ValueMember = "FeatureClassName";
        //    AddColumns(true);
        //    colaimname.SelectedValueChanged += colaimname_SelectedValueChanged;
        //    ImpDataByLyr = false;
        //}
        
        #endregion
    }
}
